package com.cet.controller;

import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.codec.multipart.Part;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.awt.*;
import java.io.File;
import java.rmi.ServerException;
import java.time.Duration;

@RestController
public class HelloController {

    // 兼容SpringMVC原先的api
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "key", required = false, defaultValue = "哈哈哈") String key) {
        return "Hello World! " + key;
    }

    @GetMapping("/haha")
    public Mono<String> haha() {
        return Mono.just("Haha World!");
    }

    @GetMapping("/ft")
    public Flux<String> fluxTest() {
        return Flux.just("f1", "f2", "f3");
    }

    // sse : server send event
    
    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> sseTest01() {
        return Flux.range(1, 100)
                .map(i -> "ha" + i)
                .delayElements(Duration.ofMillis(500));
    }

    @GetMapping(value = "/sse/new", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> sseTest02() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(i -> ServerSentEvent.builder("ha-" + i)
                        .id(i + "")
                        .comment("he-" + i)
                        .event("haha")
                        .build())
               ;
    }

    @GetMapping("/req-args")
    public Mono<Void> testRequestArgs(ServerWebExchange exchange, WebSession session) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        session.getAttributes().put("aaa", 123);

        return Mono.empty();
    }

    @PostMapping("/upload")
    public Mono<Void> handle(@RequestPart("meta-data") Part metadata,
                         @RequestPart("file-data") FilePart file) {
        // ...

        return file.transferTo(new File("C://a.txt"));
    }
}
